﻿using PermissionBLL;
using PermissionCommon;
using PermissionEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;

namespace PermissionWeb.Controllers
{
    public class LoginController : Controller
    {
        // GET: Login
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 处理用户登录
        /// </summary>
        /// <param name="userModel"></param>
        /// <param name="CookieExpires"></param>
        /// <returns></returns>
        public ActionResult CheckUserLogin(UserEntity userModel,string CookieExpires)
        {
            try
            {
                UserEntity currentUser = new UserBLL().UserLogin(userModel.AccountName, Md5.GetMD5String(userModel.Password));
                if(currentUser != null)
                {
                    if (currentUser.IsAble == false)
                    {
                        return Content("用户已被禁用，请您联系管理员");
                    }
                    // 记录登录Cookie
                    CookiesHelper.SetCookie("UserID", AES.EncryptStr(currentUser.ID.ToString()));
                    return Content("OK");
                }
                else
                {
                    return Content("用户名密码错误，请检查");
                }
            }
            catch (Exception ex)
            {
                return Content("登录异常,"+ex.Message);
            }
        }

        public ActionResult UserLoginOut()
        {
            //清空cookie
            CookiesHelper.AddCookie("UserID", System.DateTime.Now.AddDays(-1));
            return Content("{\"msg\":\"退出成功！\",\"success\":true}");
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult GetValidatorGraphics()
        {
            string code = new ValidatorCodeBLL().NewValidateCode();
            //采用cookie
            CookiesHelper.SetCookie("ValidatorCode", code);
            byte[] graphic = new ValidatorCodeBLL().NewValidateCodeGraphic(code);
            return File(graphic, @"image/jpeg");
        }
    }
}